<template>
  <div class="blog-comment-container">
    <MessageArea title="评论列表" :subTitle="`(${data.total})`" :list="data.rows" :isLoading="isLoading" @submit="handleSubmit" />
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea"
import fetchData from "@/mixins/fetchData.js"
import { getComments,postComment } from "@/api/blog.js"
export default {
  components: { MessageArea },
  mixins: [fetchData({ total: 0, rows: [] })],
  data() {
    return {
      page: 1,
      limit: 10
    }
  },
  created(){
    this.$bus.$on("mainScroll",this.handlerScroll)
  },
  destroy(){
    this.$bus.$off("mainScroll",this.handlerScroll)
  },
  computed:{
    hasMore(){
      return this.data.rows.length < this.data.total
    }
  },
  methods: {
    async fetchData() {
      return await getComments(this.$route.params.id, this.page, this.limit);
    },
    //加载下一页
    async fetchMore(){
      if(!this.hasMore){
        //没有更多的数据了
        return;
      }
      this.isLoading = true;
      this.page ++;
      const resp = await this.fetchData();
      this.data.total = resp.total;
      this.data.rows = this.data.rows.concat(resp.rows);
      this.isLoading = false;
    },
    async handlerScroll(dom){
      
      if(this.isLoading || !dom){
        //目前正在加载更多
        return;
      }
      const range = 100; //误差范围,范围内都算到达底部
      const dec = Math.abs((dom.scrollTop + dom.clientHeight) - dom.scrollHeight);
      if(dec <=range){
        this.fetchMore();
      }
    },
    async handleSubmit(formatData,callback){
      const resp = await postComment({
        blogId:this.$route.params.id,
        ...formatData,
      });
      this.data.rows.unshift(resp);
      this.data.total ++;
      callback("评论成功");  //告诉子组件我这边完成了，你继续
    }
  }
}
</script>

<style scoped lang="less">
.blog-comment-container {
  margin: 30px 0;
}
</style>